// 引用全局对象
var app = getApp();
var util = require('../../utils/util');

Page({
  data: {
    inTheaters: {},
    comingSoon: {},
    top250: {}
  },
  
  onLoad: function (event) {
    // '?start=0&count=3' 代表请求从第0开始 0 1 2，请求3条数据
    var inTheatersUrl = app.globalData.doubanbase
     + '/v2/movie/in_theaters' + '?start=1&count=3';
    var comingSoonUrl = app.globalData.doubanbase
      + '/v2/movie/coming_soon' + '?start=1&count=3';
    var top250Url = app.globalData.doubanbase
      + '/v2/movie/top250' + '?start=0&count=3';

    this.getMovieListData(inTheatersUrl, 'inTheaters', '正在热映');
    this.getMovieListData(comingSoonUrl, 'comingSoon', '即将上映');
    this.getMovieListData(top250Url, 'top250', '豆瓣Top250');
    
  },

  onMoreTap: function (event) {
    // 获取当前点击的分类，用作标识
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      url: './more-movie/more-movie?category=' + category
    });
  },

  // 获取指定url里的数据
  getMovieListData: function (url, settedKey, categoryTitle) {
    var that = this;
    wx.request({
      url: url,
      data: {
      },
      method: 'GET',
      header: {
        'Content-Type': 'json'
      },
      success: function (res) {
        that.processDoubanData(res.data, settedKey, categoryTitle);
      },
      fail: function (error) {
        console.log(error);
      }
    });
  },

  processDoubanData: function (moviesDouban, settedKey, categoryTitle) {
    // 定义数组，存储数据
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx];
      var title = subject.title;
      if (title.length >= 6) {
        // 如果标题大于等于6位，则截取6位，后面用...表示
        title = title.substring(0, 6) + '...';
      }
      // 定义temp对象，存储电影数据
      var temp = {
        movieId: subject.id,
        coverageUrl: subject.images.large,
        title: title,
        average: subject.rating.average,
        stars: util.convertToStarArray(subject.rating.stars)
      };
      movies.push(temp);
    }

    // 下面的代码有疑问
    var readyData = {};
    // 将键名作为readyData对象的属性名，对应值为一个对象
    readyData[settedKey] = {
      categoryTitle: categoryTitle,
      movies: movies
    };
    // console.log(readyData);
    this.setData(readyData);
  }
})